package by.home;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.ArrayList;


public class ChatService implements ChatServiceInterface {

  private HibernateTemplate hibernateTemplate;

  @Override
  @Transactional
  public ChatRoom createChatRoom(String header) {
    ChatRoom chatRoom = new ChatRoom(header);
    hibernateTemplate.save(chatRoom);
    hibernateTemplate.flush();
    return chatRoom;
  }

  @Override
  @Transactional
  public boolean createMessage(String content, String author, int chatRoomId) {
    return false;
  }

  @Override
  @Transactional
  public ChatRoom getChatRoomWithMessages(final int chatRoomId) {
    ChatRoom chatRoom = (ChatRoom) hibernateTemplate.executeWithNativeSession(new HibernateCallback() {
      @Override
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
        Query query = session.createQuery("From ChatRoom AS chatroom left join fetch chatroom.messages WHERE chatroom.id = :crid");
        query.setParameter("crid", chatRoomId);
        return query.list().get(0);
      }
    });
    return chatRoom;
  }

  @Override
  @Transactional
  public ChatRoom getChatRoom(int chatRoomId) {
    return null;
  }

  @Override
  @Transactional
  public boolean updateChatRoomContent(int chatRoomId, String content) {
    return false;
  }

  @Override
  @Transactional
  public ArrayList<ChatRoom> getAllChatRooms() {
    ArrayList<ChatRoom> chatRooms = (ArrayList<ChatRoom>) hibernateTemplate.executeWithNativeSession(new HibernateCallback() {
      @Override
      public Object doInHibernate(Session session) throws HibernateException, SQLException {
        return session.createQuery("FROM ChatRoom ORDER BY id").list();
      }
    });
    return chatRooms;
  }

  @Override
  public void setUserOnline(int chatRoomId) {
  }

  @Override
  public void setUserOffline(int chatRoomId) {
  }

  public HibernateTemplate getHibernateTemplate() {
    return hibernateTemplate;
  }

  public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
    this.hibernateTemplate = hibernateTemplate;
  }
}
